package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.BizPurchaseReturn;
import com.ruoyi.system.service.IBizPurchaseReturnService;
import com.ruoyi.system.service.IBizInspectionPlanService;
import com.ruoyi.system.domain.BizInspectionPlan;
import java.math.BigDecimal;

@RestController
@RequestMapping("/system/return")
public class BizPurchaseReturnController extends BaseController {

    @Autowired
    private IBizPurchaseReturnService bizPurchaseReturnService;

    @Autowired
    private com.ruoyi.web.support.SupplierContext supplierContext;

    @Autowired
    private IBizInspectionPlanService bizInspectionPlanService;

    @PreAuthorize("@ss.hasPermi('system:return:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizPurchaseReturn query) {
        supplierContext.resolveCurrentSupplierCode().ifPresent(query::setSupplierCode);
        startPage();
        List<BizPurchaseReturn> list = bizPurchaseReturnService.selectBizPurchaseReturnList(query);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('system:return:export')")
    @Log(title = "采购退料单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizPurchaseReturn query) {
        supplierContext.resolveCurrentSupplierCode().ifPresent(query::setSupplierCode);
        List<BizPurchaseReturn> list = bizPurchaseReturnService.selectBizPurchaseReturnList(query);
        ExcelUtil<BizPurchaseReturn> util = new ExcelUtil<>(BizPurchaseReturn.class);
        util.exportExcel(response, list, "采购退料单数据");
    }

    @PreAuthorize("@ss.hasPermi('system:return:query')")
    @GetMapping(value = "/{returnId}")
    public AjaxResult getInfo(@PathVariable("returnId") Long returnId) {
        return AjaxResult.success(bizPurchaseReturnService.selectBizPurchaseReturnByReturnId(returnId));
    }

    @PreAuthorize("@ss.hasPermi('system:return:add')")
    @Log(title = "采购退料单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizPurchaseReturn body) {
        supplierContext.resolveCurrentSupplierCode().ifPresent(body::setSupplierCode);
        return toAjax(bizPurchaseReturnService.insertBizPurchaseReturn(body));
    }

    @PreAuthorize("@ss.hasPermi('system:return:edit')")
    @Log(title = "采购退料单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizPurchaseReturn body) {
        supplierContext.resolveCurrentSupplierCode().ifPresent(body::setSupplierCode);
        return toAjax(bizPurchaseReturnService.updateBizPurchaseReturn(body));
    }

    @PreAuthorize("@ss.hasPermi('system:return:remove')")
    @Log(title = "采购退料单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{returnIds}")
    public AjaxResult remove(@PathVariable Long[] returnIds) {
        return toAjax(bizPurchaseReturnService.deleteBizPurchaseReturnByReturnIds(returnIds));
    }

    /**
     * 检验完成且拒收后，基于检验计划生成退料单
     * - 供应商用户将自动校验计划的供应商编码与自身是否一致
     */
    @PreAuthorize("@ss.hasPermi('system:return:add')")
    @Log(title = "采购退料单生成", businessType = BusinessType.INSERT)
    @PostMapping("/generateFromInspection")
    public AjaxResult generateFromInspection(@RequestParam String planNo,
                                             @RequestParam(required = false) BigDecimal quantity,
                                             @RequestParam(required = false) String reason,
                                             @RequestParam(required = false) Long barcodeId) {
        // 若当前为供应商用户，限制只能为自身供应商的计划生成退料单
        java.util.Optional<String> supplierOpt = supplierContext.resolveCurrentSupplierCode();
        if (supplierOpt.isPresent()) {
            BizInspectionPlan planQuery = new BizInspectionPlan();
            planQuery.setPlanNo(planNo);
            java.util.List<BizInspectionPlan> plans = bizInspectionPlanService.selectBizInspectionPlanList(planQuery);
            if (plans == null || plans.isEmpty()) {
                return AjaxResult.error("检验计划不存在: " + planNo);
            }
            if (!supplierOpt.get().equals(plans.get(0).getSupplierCode())) {
                return AjaxResult.error("无权为其他供应商生成退料单");
            }
        }
        BizPurchaseReturn created = bizPurchaseReturnService.generateFromInspectionPlan(planNo, quantity, reason, barcodeId);
        // 生成退料单后，触发拒收回滚流程，将前置流程回到采购订单生成箱码阶段
        bizInspectionPlanService.rejectAndRollback(planNo);
        return AjaxResult.success(created);
    }
}